var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var redis = require('redis');
var RedisStore = require('connect-redis')(session);

var ueditor = require("ueditor");                      //百度文本编辑器。


var config = require('config-lite')(__dirname);
var winston = require('winston');
var expressWinston = require('express-winston');
var router = require('./routes');
var users = require('./routes/users');
var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

var redisClient = redis.createClient(6379, '127.0.0.1');

// 设置Express的Session存储中间件
app.use(session({
    name: config.session.key,
    secret: config.session.secret,
    store: new RedisStore({client: redisClient}),
    resave: true,
    saveUninitialized: false,
    cookie: {
        maxAge: config.session.maxAge
    }
}));


/*app.use(session({
 name: config.session.key,
 secret: config.session.secret,
 resave: true,
 saveUninitialized: false,
 cookie: {
 maxAge: config.session.maxAge
 },
 store: new MongoStore({
 url: config.mongodb
 })
 }));*/

app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
    res.locals.id = req.session._id;
    res.locals.user = req.session.name;
    res.locals.admin = req.session.admin;
    next();
});

router(app);
app.use('/users', users);

app.use("/ueditor/ue", ueditor(path.join(__dirname, 'public'), function (req, res, next) {
    // ueditor 客户发起上传图片请求
    var img_url = '/images/ueditor';
    var actionType = req.query.action;
    if (actionType === 'uploadimage' || actionType === 'uploadfile' || actionType === "uploadvideo") {
        var file_url = img_url;
        if (actionType === 'uploadfile') {
            file_url = '/file/ueditor';
        }
        if (actionType === "uploadvideo") {
            file_url = '/video/ueditor';
        }
        res.ue_up(file_url); //你只要输入要保存的地址 。保存操作交给ueditor来做
        res.setHeader('Content-Type', 'text/html');
    } else if (req.query.action === 'listimage') {
        res.ue_list(img_url); // 客户端会列出 dir_url 目录下的所有图片
    } else {
        res.setHeader('Content-Type', 'application/json');
        res.redirect('/ueditor/config.json');
        //res.redirect('/ueditor/php/config.json');  //这里的路径要加载对否则就不能上传图片。如果你下载的是JSP那就对应jsp目录
    }
}));

app.use(expressWinston.logger({
    transports: [
        new (winston.transports.Console)({
            json: true,
            colorize: true
        }),
        new winston.transports.File({
            filename: 'logs/success.log'
        })
    ]
}));

app.use(expressWinston.errorLogger({
    transports: [
        new winston.transports.Console({
            json: true,
            colorize: true
        }),
        new winston.transports.File({
            filename: 'logs/error.log'
        })
    ]
}));
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

app.use(function (err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
